<?php
/**
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * This license is also available via the world-wide-web at
 * http://itdapps.ncsu.edu/bsd.txt
 *
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to itappdev@ncsu.edu so we can send you a copy immediately.
 *
 * @package    Index_Controller
 * @category   Controller
 * @copyright  Copyright (c) 2007 NC State University Office of Information Technology
 * @license    http://itdapps.ncsu.edu/bsd.txt  BSD License
 * @version    SVN: $Id: $
 */

/**
 * Main controller for the application
 *
 * @package    Manage_Controller
 * @category   Controller
 * @copyright  Copyright (c) 2010 NC State University Office of Information Technology
 */
class ManageController extends Zend_Controller_Action 
{   
          
    /**
     * shows the homepage
     *
     */
    public function indexAction()
    {    	
      $googleAccount = new Google_Accounts();
      
      $where = $googleAccount->getAdapter()->quoteInto('accountId = ?', Zend_Auth::getInstance()->getIdentity()->accountId);
      $accountList = $googleAccount->fetchAll($where);
      $this->view->accountList = $accountList->toArray();
      
      $this->_helper->pageTitle('My Google Accounts');
      
	}
    
	public function addAccountAction()
    {
        $get = Zend_Registry::get('getFilter');
        
        $googleAccount = new Google_Accounts();
        
        $form = $googleAccount->form();
        
        $messages = array();
        
        if ($this->_request->isPost()) {
        	if ($form->isValid($_POST)) {
        		
        		$data = array(
        		    'gmailUsername' => $form->getValue('gmailUsername'),
        		    'accountId'     => Zend_Auth::getInstance()->getIdentity()->accountId
        		);
        		
        		$dba = $googleAccount->getAdapter();
        		
        		$dba->beginTransaction();
        		
        		try {
        		    $gmailAcctId = $googleAccount->insert($data);
        		} catch (Exception $e) {
        			$dba->rollback();
        			throw $e;
        		}
                      
	            $dba->commit();
	            
	            $subcalendar = new Google_Subcalendars();
	            
	            $subCalData = array(
        			'identifier' => 'default',
	            	'gmailAcctId' => $gmailAcctId,
        		    'gmailSubCalendarId' => $form->getValue('gmailUsername')
        		);
        		
        		$dba = $subcalendar->getAdapter();
        		
        		$dba->beginTransaction();
        		
        		try {
        		    $subCalendarId = $subcalendar->insert($subCalData);
        		} catch (Exception $e) {
        			$dba->rollback();
        			throw $e;
        		}
                      
	            $dba->commit();
	                        		
		        $this->_helper->flashMessenger->addMessage('Account added successfully.');
        		
                $this->_helper->redirector->gotoRoute(array('module' => 'default', 'controller' => 'manage', 'action' => 'index'), 'default', true);
            } else {
        		$messages[] = 'There was an error adding the account.';
        	}
        }
        
        $this->_helper->pageTitle('Add new Google Calendar Account');
        $this->view->form = $form;
        $this->view->messages = $messages;
    }
    
    
    /**
     * Edit a event
     *
     */
    public function editAccountAction()
    {       
        $get = Zend_Registry::get('getFilter');
        
        $googleAccount = new Google_Accounts();
        
        $thisAccount = $googleAccount->find($get->gmailAcctId);
        
    	$permission = new Permission();
    	$owner = $permission->isAccountOwner($get->gmailAcctId, Zend_Auth::getInstance()->getIdentity()->accountId);
        
        if (!$owner) {
        	throw new Ot_Exception_Input('You are not the owner of this account record.');
        }
        
        if (is_null($thisAccount)) {
            throw new Ot_Exception_Data('The account requested was not found.');
        }
        
        $form = $googleAccount->form($thisAccount->toArray());
        
        $messages = array();
        
        if ($this->_request->isPost()) {
            if ($form->isValid($_POST)) {
                
                $data = array(
                    'gmailAcctId'   => $thisAccount->gmailAcctId,
                    'accountId'		=> Zend_Auth::getInstance()->getIdentity()->accountId,
                    'gmailUsername' => $form->getValue('gmailUsername')
                );
                
                $dba = $googleAccount->getAdapter();
                
                $dba->beginTransaction();
                
                try {
                    $googleAccount->update($data, null);
                } catch (Exception $e) {
                    $dba->rollback();
                    throw $e;
                }
                      
                $dba->commit();                
	                
                $this->_helper->flashMessenger->addMessage('The account was successfully modified.');
                
                $this->_helper->redirector->gotoRoute(array('module' => 'default', 'controller' => 'manage', 'action' => 'index'), 'default', true);
            } else {
                $messages[] = 'There was an error modifying this account.';
            }
        }
        
        $this->view->form = $form;
        $this->view->messages = $messages;
        $this->_helper->pageTitle('Edit Account');
    }
    
    public function removeAccountAction() 
    {
		$get = Zend_Registry::get('getFilter');
    	
		$googleAccount = new Google_Accounts();
		
    	$thisAccount = $googleAccount->find($get->gmailAcctId);
        
    	$permission = new Permission();
    	$owner = $permission->isAccountOwner($get->gmailAcctId, Zend_Auth::getInstance()->getIdentity()->accountId);
        
        if (!$owner) {
        	throw new Ot_Exception_Input('You are not the owner of this account record.');
        }
        
        if (is_null($thisAccount)) {
            throw new Ot_Exception_Data('The account requested was not found.');
        }
        
        $form = $googleAccount->removeAccountForm();
		
        if ($this->_request->isPost()) {
            if ($form->isValid($_POST)) {
    			
            	$googleAccount->delete($googleAccount->getAdapter()->quoteInto('gmailAcctId = ?', $thisAccount->gmailAcctId));
            	
            	$subCalendar = new Google_Subcalendars();
            	$subCalendar->delete($subCalendar->getAdapter()->quoteInto('gmailAcctId = ?', $thisAccount->gmailAcctId));
            	
            	$this->_helper->flashMessenger->addMessage('Account removed successfully.');
            	
            	$this->_helper->redirector->gotoRoute(array('module' => 'default', 'controller' => 'manage', 'action' => 'index'), 'default', true);
            }
        }
        
        $this->view->thisAccount = $thisAccount;

        $this->view->form = $form;
    	
    }
    
    /*
     *  SUB CALENDAR MANAGEMENT
     */
    
    
	public function subcalendarAction()
    {    	
      	$get = Zend_Registry::get('getFilter');
    	
    	$googleAccount = new Google_Accounts();	
      	$thisAccount = $googleAccount->find($get->gmailAcctId);
    	if ($thisAccount->accountId != Zend_Auth::getInstance()->getIdentity()->accountId) {
        	throw new Ot_Exception_Input('You are not the owner of this account record.');
        }
        
        $subCalendar = new Google_Subcalendars();
      	$where = $subCalendar->getAdapter()->quoteInto('gmailAcctId = ?', $get->gmailAcctId);
      	$subCalendarList = $subCalendar->fetchAll($where);
	    
      	
      	$this->view->gmailAcct = $get->gmailAcctId;
	    $this->view->subCalendarList = $subCalendarList->toArray();
	    $this->_helper->pageTitle('Subcalendar List');
	    
	    $this->view->messages = $this->_helper->flashMessenger->getMessages();
      
	}
    
	public function addSubcalendarAction()
    {
        $get = Zend_Registry::get('getFilter');
        
        $googleAccount = new Google_Accounts();	
      	$thisAccount = $googleAccount->find($get->gmailAcctId);
    	if ($thisAccount->accountId != Zend_Auth::getInstance()->getIdentity()->accountId) {
        	throw new Ot_Exception_Input('You are not the owner of this account record.');
        }
        
        $subCalendar = new Google_Subcalendars();
      	$where = $subCalendar->getAdapter()->quoteInto('gmailAcctId = ?', $get->gmailAcctId);
      	$subCalendarList = $subCalendar->fetchAll($where);
        
        $form = $subCalendar->form();
        
        $messages = array();
        
        if ($this->_request->isPost()) {
        	if ($form->isValid($_POST)) {
        		
        		if($subCalendar->checkIdentifierExists($form->getValue('identifier'))) {
        			$this->_helper->flashMessenger->addMessage('The identifier "'. $form->getValue('identifier') . '" has already been used. Please choose another.');
        			$this->_helper->redirector->gotoRoute(array('module' => 'default', 'controller' => 'manage', 'action' => 'add-subcalendar','gmailAcctId' => $get->gmailAcctId), 'default', true);
        		}
        		
        		
        		$data = array(
        		    'gmailAcctId'				=> $get->gmailAcctId,
        			'identifier' 				=> $form->getValue('identifier'),
        		    'gmailSubCalendarId'     	=> $form->getValue('gmailSubCalendarId')
        		);
        		
        		$dba = $subCalendar->getAdapter();
        		
        		$dba->beginTransaction();
        		
        		try {
        		    $subCalendarId = $subCalendar->insert($data);
        		} catch (Exception $e) {
        			$dba->rollback();
        			throw $e;
        		}
                      
	            $dba->commit();
	                        		
		        $this->_helper->flashMessenger->addMessage('Sub-Calendar added successfully.');
        		
                $this->_helper->redirector->gotoRoute(array('module' => 'default', 'controller' => 'manage', 'action' => 'subcalendar','gmailAcctId' => $get->gmailAcctId), 'default', true);
            } else {
        		$this->_helper->flashMessenger->addMessage('There was an error adding this sub-calendar.');
        	}
        }
        
        $this->_helper->pageTitle('Add new Google Sub-Calendar');
        $this->view->form = $form;
        $this->view->messages = $this->_helper->flashMessenger->getMessages();
    }
    
    public function editSubcalendarAction()
    {       
        $get = Zend_Registry::get('getFilter');
        
    	$permission = new Permission();
        $owner = $permission->isSubCalendarOwner($get->subCalendarId, Zend_Auth::getInstance()->getIdentity()->accountId);
        if(!$owner) {
        	$this->_helper->flashMessenger->addMessage('You are not the owner of that resource.');
        	$this->_helper->redirector->gotoRoute(array('module' => 'default', 'controller' => 'manage', 'action' => 'subcalendar','gmailAcctId' => $get->gmailAcctId), 'default', true);
        }
        
    	$subCalendar = new Google_Subcalendars();
      	$thisSubCalendar = $subCalendar->find($get->subCalendarId);
      	$calendarArray = $thisSubCalendar->toArray();
        $form = $subCalendar->form($calendarArray);
        
        $messages = array();
        
        if ($this->_request->isPost()) {
        	if ($form->isValid($_POST)) {
        		
        		if($subCalendar->checkIdentifierExists($form->getValue('identifier'))) {
        			$this->_helper->flashMessenger->addMessage('The identifier "'. $form->getValue('identifier') . '" has already been used. Please choose another.');
        			$this->_helper->redirector->gotoRoute(array('module' => 'default', 'controller' => 'manage', 'action' => 'edit-subcalendar','subCalendarId' => $get->subCalendarId), 'default', true);
        		}
        
        
        		
        		$data = array(
        		    'subCalendarId'				=> $get->subCalendarId,
        			'identifier' 				=> $form->getValue('identifier'),
        		    'gmailSubCalendarId'     	=> $form->getValue('gmailSubCalendarId')
        		);
        		
        		$dba = $subCalendar->getAdapter();
        		
        		$dba->beginTransaction();
        		
        		try {
        		    $subCalendarId = $subCalendar->update($data);
        		} catch (Exception $e) {
        			$dba->rollback();
        			throw $e;
        		}
                      
	            $dba->commit();
	                        		
		        $this->_helper->flashMessenger->addMessage('Sub-calendar edited successfully.');
        		
                $this->_helper->redirector->gotoRoute(array('module' => 'default', 'controller' => 'manage', 'action' => 'subcalendar','gmailAcctId' => $thisSubCalendar->gmailAcctId), 'default', true);
            } else {
        		$messages[] = 'There was an error adding the sub-calendar.';
        	}
        }
        
        $this->_helper->pageTitle('Modify Google Sub-Calendar');
        $this->view->form = $form;
        $this->view->messages = $messages;
        $this->view->messages = $this->_helper->flashMessenger->getMessages();
    }
    
    public function removeSubcalendarAction() 
    {
		$get = Zend_Registry::get('getFilter');
    	
		$subCalendar = new Google_Subcalendars();
		
    	$thisSubcalendar = $subCalendar->find($get->subCalendarId);
    	
    	if($thisSubcalendar['identifier'] == 'default') {
    		$this->_helper->flashMessenger->addMessage('You cannot remove or edit default account.');
        	$this->_helper->redirector->gotoRoute(array('module' => 'default', 'controller' => 'manage', 'action' => 'subcalendar','gmailAcctId' => $get->gmailAcctId), 'default', true);
    	}
        
    	$permission = new Permission();
        $owner = $permission->isSubCalendarOwner($get->subCalendarId, Zend_Auth::getInstance()->getIdentity()->accountId);
        if(!$owner) {
        	throw new Ot_Exception_Input('You are not the owner of this account record.');
        }
        
        $form = $subCalendar->removeSubcalendarForm();
		
        if ($this->_request->isPost()) {
            if ($form->isValid($_POST)) {
            	
            	$subCalendar->delete($subCalendar->getAdapter()->quoteInto('subCalendarId = ?', $get->subCalendarId));
            	$this->_helper->flashMessenger->addMessage('Sub-calendar removed successfully.');
            	$this->_helper->redirector->gotoRoute(array('module' => 'default', 'controller' => 'manage', 'action' => 'subcalendar','gmailAcctId' => $thisSubcalendar->gmailAcctId), 'default', true);
            }
        }
        
        $this->_helper->pageTitle('Remove Sub-Calendar');
        $this->view->thisSubcalendar = $thisSubcalendar;

        $this->view->form = $form;
    	
    }
    
		
}

